<template>
<!--我的订单-->
  <div class="orders">
      <div class="titleWrap">
        <p class="titleName">申请发票</p>
      </div>
      <div class="formWrapper ziliao">
        <Form :label-width="102" label-position="left" ref="invoiceForm" :model="invoice" :rules="invoiceRules">
          <FormItem label="发票类型">
            <RadioGroup v-model="invoice.einvoice">
              <Radio :label="1" >电子发票</Radio>
              <Radio :label="0" >纸质发票</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="发票内容" class="text">{{invoice.invoiceBody}}</FormItem>
          <FormItem label="商品金额" class="text">￥{{invoice.invoiceAmount}}</FormItem>
          <FormItem label="抬头类型">
            <RadioGroup v-model="invoice.invoiceType" >
              <Radio :label=1 @click="personChose" v-if="invoice.einvoice == 0">个人发票</Radio>
              <Radio :label=2 >企业发票</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="" class="other_item">
            <RadioGroup v-model="invoice.invoiceKind" v-if="invoice.einvoice == 0">
              <!--<Radio :label=1 >增值税普通发票</Radio>-->
              <Radio :label=0 v-if="invoice.einvoice == 0 && invoice.invoiceType == 2" >增值税专用发票</Radio>
            </RadioGroup>
          </FormItem>
            <FormItem label="发票抬头" prop="invoiceTitle" v-if="invoice.invoiceType == 2">
              <AutoComplete  :maxlength="35" v-model="invoice.invoiceTitle" @on-search="searchNo"  placeholder="必填，营业执照上的名称" style="width:250px" @on-change="chooseCompany">
                <Option v-for="option in companies" :value="option.name" :key="option.name">
                  <span class="demo-auto-complete-title">{{ option.name}}</span>
                  <!--<span class="demo-auto-complete-count">{{ option.kpCode }}</span>-->
                </Option>
              </AutoComplete>
            </FormItem>
            <FormItem label="发票抬头" prop="invoiceTitle" v-if="invoice.invoiceType == 1">
              <Input class="formWidth" placeholder="必填，请输入证件上的姓名" v-model="invoice.invoiceTitle" :maxlength="35"/>
            </FormItem>
          <FormItem label="企业税号" prop="creditCode" v-if="invoice.invoiceType == 2">
              <Input class="formWidth" placeholder="必填，企业税号" v-model="invoice.creditCode" :maxlength="20"/>
            </FormItem>
            <FormItem label="注册地址" prop="enterpriseAddress" v-if="invoice.invoiceType == 2 && invoice.einvoice == 0">
              <Input class="formWidth" placeholder="必填，公司注册地址" v-model="invoice.enterpriseAddress" :maxlength="90"/>
            </FormItem>
            <FormItem label="公司电话" prop="enterpriseTel" v-if="invoice.invoiceType == 2 && invoice.einvoice == 0">
              <Input class="formWidth" placeholder="必填，区号-总机" v-model="invoice.enterpriseTel" :maxlength="15"/>
            </FormItem>
            <FormItem label="开户银行" prop="bankName" v-if="invoice.invoiceType == 2 && invoice.einvoice == 0">
              <Input class="formWidth" placeholder="必填，对外付款的开户行" v-model="invoice.bankName" :maxlength="45"/>
            </FormItem>
            <FormItem label="开户账号" prop="bankNo" v-if="invoice.invoiceType == 2 && invoice.einvoice == 0">
              <Input class="formWidth" placeholder="必填，对外付款的银行账号" v-model="invoice.bankNo" :maxlength="45"/>
            </FormItem>
            <FormItem label="收件人" prop="consignee" v-if="invoice.einvoice == 0">
              <Input class="formWidth" placeholder="必填，请输入收件人姓名" v-model="invoice.consignee" :maxlength="15"/>
            </FormItem>
            <FormItem label="手机号码" prop="telephone">
              <Input class="formWidth" placeholder="必填，请输入手机号" v-model="invoice.telephone" :maxlength="11"  ref="phoneapply"  @on-keyup="validatePhone"/>
            </FormItem>
            <FormItem label="收件地址" prop="address" v-if="invoice.einvoice == 0">
              <Input class="formWidth" placeholder="必填，请输入你的收件地址" v-model="invoice.address" :maxlength="85"/>
            </FormItem>
            <FormItem label="电子邮箱" prop="email" v-if="invoice.einvoice == 1">
              <Input class="formWidth" placeholder="必填，请输入您的电子邮箱" v-model="invoice.email" :maxlength="45"/>
            </FormItem>
            <div class="tip font14">注：纸质发票按您提交的地址邮寄，默认发顺丰快递，邮费到付。</div>
          <FormItem label="">
            <div class="keepThis"><span class="keepBtn" @click="submit">提交</span></div>
          </FormItem>

        </Form>
        <Spin fix v-show="isSpinShow" >
          <div class="loader">
            <Icon type="ios-loading" size=26 class="demo-spin-icon-load"></Icon>
            <div class="font14">加载中...</div>
          </div>
        </Spin>
      </div>
  </div>
</template>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less" rel="stylesheet/less">

  /* 旋转效果 */
  .demo-spin-icon-load{
    animation: ani-demo-spin 1s linear infinite;
  }
  @keyframes ani-demo-spin {
    from { transform: rotate(0deg);}
    50% { transform: rotate(180deg);}
    to { transform: rotate(360deg);}
  }
  /* 假如内容过长，一屏放不下，滚动条下拉覆盖不全 */
  .ivu-spin-fix {
    position: fixed;
  }

  .other_item{
    margin-top: -20px;
  }
  .titleWrap {
    height: 40px;
    font-size: 18px;
    padding-bottom: 20px;
    text-align: justify-all;
    border-bottom: 1px solid #E1E1E1;
    margin-bottom: 20px;
    color: #957960;
    .titleName {
      float: left;
      line-height: 24px;
      border-bottom: 3px solid #957960;
      padding-bottom: 13px;
    }
  }
  .formWrapper .ivu-form-item{
    width: 350px;
  }
  .tip{
    color: #ff6600;
    /*font-size: 16px;*/
    margin:0 0 25px 102px;
  }
  .keepBtn{
    display: inline-block;
    width: 140px;
    height: 52px;
    background-color: #957960;
    text-align: center;
    line-height: 50px;
    color: #fff;
    font-size: 18px;
    cursor: pointer;
  }

</style>
<script type="text/ecmascript-6">
  import {addInvoice,applyInvoicePage,centreInfoWeb,selectCompany,findByCompany} from '../../http'
  import {getStore} from '../../storage'
    export default {
        name: 'orderdetail',
        props: {},
        data() {
            //自定义表单验证
            const creditCodeRule = (rule, value , callback) => {
              if(value === '' && this.invoice.invoiceType == 2){
                callback(new Error('必填，请输入企业税号'))
              }else{
                if(value.length < 6 || value.length > 20) {
                  callback(new Error('请输入正确的企业税号'));
                }else {
                  callback();
                }
              }
            };
            //企业纸质：注册地址，公司电话，开户银行，开户账号
            const enterpriseAddressRule = (rule, value, callback) => {
              if(value === '' && this.invoice.invoiceType == 2 && this.invoice.einvoice == 0){
                callback(new Error('必填，请输入公司注册地址'))
              }else{
                callback();
              }
            };
            const enterpriseTelRule = (rule, value, callback) => {
              if(value === '' && this.invoice.invoiceType == 2 && this.invoice.einvoice == 0){
                callback(new Error('必填，请输入公司电话'))
              }else{
                callback();
              }
            };
            const bankNameRule = (rule, value, callback) => {
              if(value === '' && this.invoice.invoiceType == 2 && this.invoice.einvoice == 0){
                callback(new Error('必填，请输入开户银行'))
              }else{
                callback();
              }
            };
            const bankNoRule = (rule, value, callback) => {
              if(value === '' && this.invoice.invoiceType == 2 && this.invoice.einvoice == 0){
                callback(new Error('必填，请输入开户账号'))
              }else{
                callback();
              }
            };
            //纸质发票都有收件人和收件地址
            const consigneeRule = (rule, value, callback) => {
              if(value === '' && this.invoice.einvoice == 0){
                callback(new Error('必填，请输入收件人'))
              }else{
                callback();
              }
            };
            const addressRule = (rule, value, callback) => {
              if(value === '' && this.invoice.einvoice == 0){
                callback(new Error('必填，请输入收件地址'))
              }else{
                callback()
              }
            };
            const invoiceTitleRule = (rule, value, callback) => {
              if(value === '' ){
                if(this.invoice.invoiceType == 1) {
                  callback(new Error('必填，请输入证件上的姓名'))
                }
                if(this.invoice.invoiceType == 2) {
                  callback(new Error('必填，营业执照上的名称'))
                }
              }else if(value.length >44){
                callback(new Error('填写信息过多！'))
              }
              else{
                callback()
              }
            };
            const emailRule = (rule, value, callback) => {
              if(value === '' && this.invoice.einvoice === 1){
                callback(new Error('必填，请输入电子邮箱'));
              }
              if(!value.match("^[\\w\\+\\-]+(\\.[\\w\\+\\-]+)*@[a-z\\d\\-]+(\\.[a-z\\d\\-]+)*\\.([a-z]{2,4})$")) {
                callback(new Error('必填，邮箱格式不正确'));
              }
                callback();
            };
            const telephoneRule = (rule, value, callback) => {
              if(value === ''){
                callback(new Error('必填，请输入手机号'));
              }
              if(!value.match("^[1][3,4,5,7,8][0-9]{9}$")) {
                callback(new Error('必填，请输入正确手机号码'));
              }
              callback()
            };
            return {
              isSpinShow:false,
              // sear:false,
              companies:[],
              invoice:{
                invoiceBody:'',          //发票内容
                invoiceAmount:'',         //发票金额
                orderId:this.$route.query.orderId,    //订单Id
                invoiceType: 2,        ///** 发票类型1：个人发票2：企业发票 */
                einvoice: 1,           ///** 是否电子发票  0纸质 1电子 */
                invoiceKind: 0,        ///** 发票种类（1普通发票2专用发票） */
                telephone:'',           //手机号
                email:'',               //邮箱
                invoiceTitle:'',       //发票抬头
                creditCode:'',         ///** 企业代码(税号) */
                address:'',            //
                consignee:'',         ///** 收件人 */
                enterpriseAddress:'',     ///** 企业地址 */
                enterpriseTel:'',         ///** 企业电话 */
                bankName:'',              ///** 开户行 */
                bankNo:'',              ///** 账户 */
              },
              //表单验证规则
              invoiceRules:{
                //发票抬头和手机号码是都要有的
                invoiceTitle:[
                  { validator:invoiceTitleRule,trigger:'blur'}
                ],
                telephone:[
                  { validator:telephoneRule,trigger:'blur'}
                ],
                creditCode:[
                  // { validator:creditCodeRule,message:"必填，请输入企业税号",trigger:'change'}
                  { validator:creditCodeRule,trigger:'change'}
                ],
                enterpriseAddress:[
                  { validator:enterpriseAddressRule,message:"必填，请输入公司注册地址",trigger:'blur'}
                ],
                enterpriseTel:[
                  { validator:enterpriseTelRule,message:"必填，请输入公司电话",trigger:'blur'}
                ],
                bankName:[
                  { validator:bankNameRule,message:"必填，请输入开户银行",trigger:'blur'}
                ],
                bankNo:[
                  { validator:bankNoRule,message:"必填，请输入开户账号",trigger:'blur'}
                ],
                consignee:[
                  { validator:consigneeRule,message:"必填，请输入收件人",trigger:'blur'}
                ],
                address:[
                  { validator:addressRule,message:"必填，请输入收件地址",trigger:'blur'}
                ],
                email:[
                  { validator:emailRule,trigger:'blur'}
                ],
              }
            };
        },
        methods: {
          //数字输入框
          validatePhone() {
            this.invoice.telephone = this.$refs.phoneapply.value.replace(/[^\d]{1,11}/g, "")
          },
          //选择公司和税号
          chooseCompany(value){
            //从搜索结果找出code用户查询税号
            for(let j = 0,len = this.companies.length; j < len; j++){
              if(this.companies[j].name === value){
                //本身自动完成框，是有数据绑定的，当用户选择一个下拉框自动赋值
                this.invoice.invoiceTitle = value;
                findByCompany({kCode:this.companies[j].code}).then(res => {
                  this.invoice.creditCode = res.data.kpCode;
                }).catch()
              }
            }
          },
          //搜索公司和税号
          searchNo(value){
            //当用户输入三个字以上查询公司
            if(value.trim().length > 2) {
              //根据输入的发票抬头模糊搜索
              selectCompany({companyName:value}).then(res => {
                this.companies = res.data;        //搜索到的公司
              }).catch()
            }
          },
          personChose(){
            this.invoice.invoiceKind = 1;
            // this.$refs.invoiceForm.resetFields();
          },
          submit(){
            if(this.isSpinShow === false) {
              this.isSpinShow = true;
              this.$refs.invoiceForm.validate((valid) => {
                if (valid) {
                  centreInfoWeb().then(res => {
                    if (res.code === 200) {
                      addInvoice({
                        invoiceBody: this.invoice.invoiceBody,
                        invoiceAmount: this.invoice.invoiceAmount,
                        orderId: this.invoice.orderId,
                        invoiceType: this.invoice.invoiceType,
                        einvoice: this.invoice.einvoice,
                        invoiceKind: this.invoice.invoiceKind,
                        telephone: this.invoice.telephone,
                        email: this.invoice.email,
                        invoiceTitle: this.invoice.invoiceTitle,
                        creditCode: this.invoice.creditCode,
                        address: this.invoice.address,
                        consignee: this.invoice.consignee,
                        enterpriseAddress: this.invoice.enterpriseAddress,
                        enterpriseTel: this.invoice.enterpriseTel,
                        bankName: this.invoice.bankName,
                        bankNo: this.invoice.bankNo
                      }).then(res => {
                        if (res.code === 200) {
                          this.isSpinShow = false;
                          this.$Notice.success({
                            title: '发票申请结果提醒',
                            desc: '发票申请成功!',
                            duration: 3,
                          });
                          this.$router.push({
                            name: 'order',
                          })
                        } else {
                          this.isSpinShow = false;
                          this.$Notice.warning({
                            title: "发票申请结果提醒",
                            desc: res.info,
                            duration: 3,
                          });
                        }
                      }).catch()
                    } else {
                      this.isSpinShow = false;
                      this.$parent.$refs.loginInput.showModal()
                    }
                  }).catch()
                }else {
                  this.isSpinShow = false;
                }
              }).catch()
            }
          },
          getApplyFapiao(){
            if(this.isSpinShow === false) {
              this.isSpinShow = true;
              //用户是否登录
              centreInfoWeb().then(res => {
                if (res.code === 200) {
                  //获取发票页面数据
                  applyInvoicePage({orderId: this.invoice.orderId}).then(res => {
                    if(res.code === 200) {
                      this.isSpinShow = false;
                      this.invoice.invoiceAmount = res.data.amount;
                      // this.invoice.invoiceBody = res.data.content;
                      this.invoice.invoiceBody = "*生活服务*培训费";
                    }else {
                      this.isSpinShow = false;
                      this.$Notice.warning({
                        title: "个人中心提醒",
                        desc: res.info,
                        duration: 3,
                      });
                    }
                  }).catch()
                }else {
                  this.isSpinShow = false;
                }
              }).catch()
            }
          }
        },
        created() {
          this.getApplyFapiao()
        },
        components: {
        }
    }
</script>
